<script setup>
import {
  onMounted,
  onUnmounted,
  onBeforeUnmount,
  ref,
  watch,
  nextTick,
} from "vue";
import * as echarts from "echarts";
import { useScaleStore } from "@/stores/scaleStore";

const props = defineProps({
  title: {
    type: String,
    default: "内波温度断面",
  },
  gridData: {
    type: Array,
    default: () => [],
  },
  roadPath: {
    type: Array,
    default: () => [],
  },
  additionalInfo: {
    type: String,
    default: "",
  },
  closeEvent: Function,
});

const closeClick = () => {
  props?.closeEvent();
};

let profileChart = null;
let resizeObserver = null;
const chartDom = ref(null);
const boxWrapRef = ref(null);
const headerRef = ref(null);
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const currentPos = ref({ x: 0, y: 0 });
const currentScale = ref(1); // 当前窗口缩放比例
const isResizing = ref(false);
const resizeDirection = ref(null);
const startSize = ref({ width: 450, height: 350 });
const currentSize = ref({ width: 450, height: 350 });

const scaleStore = useScaleStore();

// 监听scaleStore的变化
watch(
  () => scaleStore.currentScale,
  (newScale) => {
    currentScale.value = newScale || 1;
  },
  { immediate: true }
);

const handleMouseDown = (e) => {
  // 检查是否是缩放区域
  if (e.target.classList.contains("resize-handle")) {
    isResizing.value = true;
    resizeDirection.value = e.target.dataset.direction;
    startSize.value = { ...currentSize.value };
    startPos.value = { x: e.clientX, y: e.clientY };

    e.stopPropagation();
    e.preventDefault();
    document.addEventListener("mousemove", handleResizeMove);
    document.addEventListener("mouseup", handleResizeEnd);
    return;
  }

  // 原有拖动逻辑
  if (!headerRef.value || !headerRef.value.contains(e.target)) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  isDragging.value = true;
  startPos.value = {
    x: adjustedX - currentPos.value.x,
    y: adjustedY - currentPos.value.y,
  };

  e.stopPropagation();
  e.preventDefault();

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  const newX = adjustedX - startPos.value.x;
  const newY = adjustedY - startPos.value.y;

  currentPos.value = { x: newX, y: newY };

  if (boxWrapRef.value) {
    boxWrapRef.value.style.left = `${newX}px`;
    boxWrapRef.value.style.top = `${newY}px`;
  }

  e.preventDefault();
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
};

const handleResizeMove = (e) => {
  if (!isResizing.value) return;

  const deltaX = (e.clientX - startPos.value.x) / currentScale.value;
  const deltaY = (e.clientY - startPos.value.y) / currentScale.value;

  const newSize = { ...currentSize.value };

  switch (resizeDirection.value) {
    case "e":
      newSize.width = Math.max(300, startSize.value.width + deltaX);
      break;
    case "s":
      newSize.height = Math.max(250, startSize.value.height + deltaY);
      break;
    case "se":
      newSize.width = Math.max(300, startSize.value.width + deltaX);
      newSize.height = Math.max(250, startSize.value.height + deltaY);
      break;
  }

  currentSize.value = newSize;
  updateChartSize();
  e.preventDefault();
};

const handleResizeEnd = () => {
  isResizing.value = false;
  resizeDirection.value = null;
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
};

const updateChartSize = () => {
  if (profileChart) {
    profileChart.resize();
  }
};

watch(
  () => props.gridData,
  (newVal) => {
    if (newVal && newVal.length) {
      renderProfile();
    }
  },
  { immediate: true }
);

async function initChart() {
  await nextTick();
  if (!chartDom.value) return;

  profileChart = echarts.init(chartDom.value);
  window.addEventListener("resize", () => {
    profileChart?.resize();
  });

  if (props.gridData?.length) {
    renderProfile();
  }
}

function renderProfile() {
  if (!profileChart || !props.gridData?.length || !props.roadPath?.length)
    return;

  // 1. 深度插值处理 (从7层插值到31层)
  const originalDepths = [0, 50, 100, 150, 200, 250, 300];
  const interpolatedDepths = [];
  const heatmapData = [];

  // 生成插值后的深度层（每10米一层）
  for (let i = 0; i < originalDepths.length - 1; i++) {
    const startDepth = originalDepths[i];
    const endDepth = originalDepths[i + 1];
    interpolatedDepths.push(startDepth);

    // 在每50米之间插入4个中间层（共5层）
    for (let j = 1; j < 5; j++) {
      interpolatedDepths.push(startDepth + ((endDepth - startDepth) * j) / 5);
    }
  }
  interpolatedDepths.push(300);

  // 2. 温度数据插值（线性插值）
  props.gridData.slice(0, 7).forEach((layer, depthIdx) => {
    const nextLayer = props.gridData[depthIdx + 1];

    layer.depth_layers.forEach((temp, pointIdx) => {
      // 原始数据点
      heatmapData.push([pointIdx, depthIdx * 5, temp]);

      // 插值数据点（4个中间层）
      if (nextLayer) {
        const nextTemp = nextLayer.depth_layers[pointIdx];
        for (let i = 1; i <= 4; i++) {
          const interpolatedTemp = temp + ((nextTemp - temp) * i) / 5;
          heatmapData.push([pointIdx, depthIdx * 5 + i, interpolatedTemp]);
        }
      }
    });
  });

  // 3. 增强的视觉配置
  const option = {
    title: {
      text: props.title,
      left: "center",
      textStyle: {
        color: "#38e1ff",
        fontSize: 16,
        fontWeight: "bold",
      },
      subtext: props.additionalInfo,
      subtextStyle: {
        color: "#a0dfff",
        fontSize: 14,
      },
    },
    tooltip: {
      position: "top",
      formatter: function (params) {
        const depth = interpolatedDepths[params.value[1]];
        const temp = params.value[2];
        return `深度: ${depth}m<br>温度: ${temp.toFixed(1)}°C`;
      },
    },
    grid: {
      left: "3%",
      right: "12%",
      bottom: "15%",
      top: "22%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      name: "波峰线",
      nameLocation: "middle",
      nameGap: 25,
      axisLabel: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: "#4c9bfd",
          width: 2,
        },
      },
    },
    yAxis: {
      type: "category",
      data: interpolatedDepths.map((d, i) => {
        // 只在原始深度标注温度和深度
        if (i % 5 === 0) {
          const temp = 28 - d / 18.75;
          return `${d}m\n${temp.toFixed(1)}°C`;
        }
        return "";
      }),
      name: "深度(m)",
      inverse: true,
      axisLine: {
        lineStyle: {
          color: "#4c9bfd",
          width: 2,
        },
      },
      axisLabel: {
        color: "#8eb9ff",
        fontSize: 12,
        margin: 15,
        formatter: (value) => value,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "rgba(76, 155, 253, 0.2)",
          type: "dashed",
        },
      },
    },
    visualMap: {
      min: 12,
      max: 28,
      orient: "vertical",
      right: "1%",
      top: "middle",
      text: ["28°C", "12°C"],
      inRange: {
        color: [
          "#313695",
          "#4575b4",
          "#74add1",
          "#abd9e9",
          "#e0f3f8",
          "#fee090",
          "#fdae61",
          "#f46d43",
          "#d73027",
        ],
      },
      textStyle: {
        color: "#fff",
      },
    },
    series: [
      {
        name: "温度",
        type: "heatmap",
        data: heatmapData,
        itemStyle: {
          borderWidth: 0,
          opacity: 0.9,
        },
        emphasis: {
          itemStyle: {
            borderWidth: 1,
            borderColor: "rgba(255,255,255,0.8)",
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        progressive: 1000,
      },
    ],
  };

  profileChart.setOption(option, true);
}

onMounted(async () => {
  await initChart();

  if (boxWrapRef.value) {
    const rect = boxWrapRef.value.getBoundingClientRect();
    currentPos.value = { x: rect.left, y: rect.top };
  }

  resizeObserver = new ResizeObserver(() => {
    if (profileChart) {
      profileChart.resize();
    }
  });
  resizeObserver.observe(chartDom.value);
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
  if (profileChart) {
    profileChart.dispose();
    profileChart = null;
  }
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
});

onBeforeUnmount(() => {
  if (profileChart) {
    const dom = profileChart.getDom();
    if (dom) {
      const canvas = dom.querySelector("canvas");
      if (canvas) {
        const gl =
          canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
        if (gl) {
          const loseContext = gl.getExtension("WEBGL_lose_context");
          if (loseContext) loseContext.loseContext();
        }
      }
    }
    profileChart.dispose();
    profileChart = null;
  }
});
</script>

<template>
  <div
    class="popup-container"
    :style="{
      left: `${currentPos.x}px`,
      top: `${currentPos.y}px`,
      width: `${currentSize.width}px`,
      height: `${currentSize.height}px`,
    }"
  >
    <div class="pine"></div>
    <div class="box-wrap" ref="boxWrapRef">
      <!-- 标题栏区域 -->
      <div class="header-area" ref="headerRef" @mousedown="handleMouseDown">
        <div class="title-text">{{ title }}</div>
        <div class="close" @click="closeClick">X</div>
      </div>
      <!-- 图表区域 -->
      <div ref="chartDom" class="chart-container"></div>

      <!-- 缩放控制手柄 -->
      <div
        class="resize-handle resize-e"
        data-direction="e"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-s"
        data-direction="s"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-se"
        data-direction="se"
        @mousedown="handleMouseDown"
      ></div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.popup-container {
  position: fixed;
  z-index: 9999;
  cursor: default;
  min-width: 300px;
  min-height: 250px;
}

.box-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  border: 1px solid #38e1ff;
  background-color: rgba(30, 80, 120, 0.7);
  box-shadow: 0 0 10px 2px #29baf1;
  animation: slide 1s;
  overflow: hidden;
  user-select: none;
}

/* 标题栏样式 */
.header-area {
  position: relative;
  height: 40px;
  background: linear-gradient(
    to right,
    rgba(20, 60, 100, 0.9),
    rgba(30, 80, 120, 0.9)
  );
  border-bottom: 1px solid #38e1ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  cursor: grab;

  &:active {
    cursor: grabbing;
  }
}

.title-text {
  color: #38e1ff;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(56, 225, 255, 0.7);
}

.close {
  color: #fff;
  text-shadow: 2px 2px 2px #022122;
  cursor: pointer;
  font-size: 20px;
  transition: all 0.2s;

  &:hover {
    color: #ff6b6b;
    transform: scale(1.1);
  }
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: calc(100% - 40px); /* 减去标题栏高度 */
  padding: 10px;
  box-sizing: border-box;
}

/* 缩放控制手柄样式 */
.resize-handle {
  position: absolute;
  background: transparent;
  z-index: 10;
}

.resize-e {
  cursor: e-resize;
  width: 10px;
  height: 100%;
  right: 0;
  top: 0;
}

.resize-s {
  cursor: s-resize;
  width: 100%;
  height: 10px;
  bottom: 0;
  left: 0;
}

.resize-se {
  cursor: se-resize;
  width: 15px;
  height: 15px;
  right: 0;
  bottom: 0;
  background: #38e1ff;
  opacity: 0;
  transition: opacity 0.2s;
}

.box-wrap:hover .resize-se {
  opacity: 0.8;
}

.pine {
  position: absolute;
  width: 100px;
  height: 100px;
  box-sizing: border-box;
  line-height: 120px;
  text-indent: 5px;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fontColor {
  0% {
    color: #ffffff00;
    text-shadow: 1px 1px 5px #00252000;
  }
  40% {
    color: #ffffff00;
    text-shadow: 1px 1px 5px #00252000;
  }
  100% {
    color: #ffffff;
    text-shadow: 1px 1px 5px #002520d2;
  }
}
</style>
